//Man hinh nhap diem, cho phep xem va chinh sua toan bo diem.
package www.truongnha.com;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;

import Config.setting;
import KeyboardLib.BasicOnKeyboardActionListener;
import KeyboardLib.CustomKeyboardView;
import TruongNhaLib.Diem;
import TruongNhaLib.JSONParser;
import TruongNhaLib.MarkModel;
import TruongNhaLib.UserFunctions;
import ViewPagerLib.BaseSampleActivity;
import ViewPagerLib.TestFragment;
import ViewPagerLib.TestFragmentAdapter;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.inputmethodservice.Keyboard;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Toast;

import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.AbstractAction;
import com.viewpagerindicator.TabPageIndicator;

public class SubmitMark extends BaseSampleActivity {
	//userfunction for submit mark to server
//    UserFunctions userFunction = new UserFunctions();
	//Keyboard
	private CustomKeyboardView mKeyboardView;
	private Keyboard mKeyboard;
	ActionBar actionBar;
	//const id for actions
	private static final int HOME_ID = 0;
	private static final int DATE_ID = 1;
	private static final int SUBMIT_ID = 2;
	private static final int SETTING_ID = 3; //For setting input method, on/off Suggestion or Sound effect// Implement later
	private static final int DATE_DIALOG_ID = 4;
	private String host = setting.getHost();
	private String url = host + "api/markForASubject/";
	private String url_submit_mark = host + "api/markForASubject"; //+ subject_id
	String subjectId;
	String className;
	String subject;
	
	private static final String[] CONTENT = new String[] {"Điểm miệng", "15 phút", "45 phút", "Cuối kỳ-TK" };
    //List of MarkModel for student.
    private List<MarkModel> list = new ArrayList<MarkModel>();
    //Size of the list. or the number of students in class.
    private int size = 0 ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.simple_tabs);
        //setup keyboard 
        if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
			mKeyboard = new Keyboard(this, R.xml.keyboard3rows);
		else
			mKeyboard = new Keyboard(this, R.xml.keyboard2rows);
		mKeyboardView = (CustomKeyboardView) findViewById(R.id.keyboard_view);
		mKeyboardView.setKeyboard(mKeyboard);
		mKeyboardView.setOnKeyboardActionListener(new BasicOnKeyboardActionListener(this));
		
		// getting intent data
        Intent in = getIntent();
		subjectId = in.getStringExtra("subjectId");
		subject = in.getStringExtra("subject");
		className = in.getStringExtra("class");
        actionBar = (ActionBar) findViewById(R.id.actionbar);
        actionBar.setHomeAction(new myAction(HOME_ID, R.drawable.ic_back));
        actionBar.setTitle("Lớp " + className+ " - "+ subject);
//        actionBar.addDateAction(new myAction(DATE_ID, R.drawable.ic_title_export_default));
        actionBar.addAction(new myAction( SUBMIT_ID, R.drawable.ic_title_export_default) );
//        actionBar.addAction(new myAction( 2, R.drawable.ic_title_hetpin) );
        
        //Load data from server and bind to mark model
		new getMark().execute("url to get mark");
        //analysisMarkModel();		
		mPager = (ViewPager)findViewById(R.id.pager);
        mIndicator = (TabPageIndicator)findViewById(R.id.indicator);
		mAdapter = new GoogleMusicAdapter(getSupportFragmentManager());
        mPager.setAdapter(mAdapter);
        mIndicator.setViewPager(mPager);
    }
    
    /**
     * Analysis the MarkModel
     * Get mark data from the server
     * Bind mark json to mark model
     */
    //submit a mark only
	class getMark extends AsyncTask<String, Void, Void>{
		String message;
		ProgressDialog dialog;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			message = "";
			dialog = new ProgressDialog(SubmitMark.this);
			dialog.setMessage("Loading...");
			dialog.show();
    		actionBar.setProgressBarVisibility(View.VISIBLE);
		}
		@Override
		protected Void doInBackground(String... params) {			
			JSONParser jsonParser = new JSONParser();
	    	JSONArray jArraylevel1 =  jsonParser.getJSONArray(url+ subjectId);
	    	size = jArraylevel1.length();
			Log.d("jArraylevel1", "jArraylevel1.size()=" + size );
			if(size == 1){//May be error, check error
				try {
					message = jArraylevel1.getString(0);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			Log.d("message", message);
			if(message.equals(""))//no error.
	    	try {
	    		int index = 0 ;
				for(int i = 0 ; i < size ; i++ ){
					//Log.d("bug i", "0" +i);
				  	index = i + 1;
				  	//Diem is an object mark for only one student
		            JSONObject Diem = jArraylevel1.getJSONObject(i);
		            //Analysis Diem array for a student:
		            JSONArray Diem28 = Diem.getJSONArray("mark");
		            //diemArray is a list of mark of a subject for a student
					int size28 = MarkModel.size_full;//defined 28 in MarkModel
		            Diem[] diemArray = new Diem[size28];
					for(int k = 0 ; k < size28 ; k ++) {
						diemArray[k] = new Diem(-1, true, -1, -1 ); // blank mark
					}
					for(int k = 0 ; k < Diem28.length() ; k ++) {
						JSONObject aDiem = Diem28.getJSONObject(k);					
						int number = aDiem.getInt("n");
						diemArray[number-1] = new Diem(Double.valueOf( aDiem.getString("m") ), editable(aDiem.getString("e")), number , aDiem.getInt("s"));
					}
		            list.add( new MarkModel(Diem.getString("id"), index, Diem.getString("firstName"), diemArray, Diem.getString("lastName"), Diem.getString("firstName") ) );
				}//end for.
				Log.d("bug", "end for");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}//end try.			
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			dialog.dismiss();
			if(message.equals("")){// no error
				mAdapter = new GoogleMusicAdapter(getSupportFragmentManager());
				mPager.setAdapter(mAdapter);
				mIndicator.setViewPager(mPager);
				
			} else{ //error
				Toast.makeText(getApplicationContext(), message,Toast.LENGTH_SHORT).show();
			}
			actionBar.setProgressBarVisibility(View.GONE);
		}
	}//End class

    private void analysisMarkModel() {
		// TODO Auto-generated method stub
        //Load mark data from Server:
    	Log.d("submit mart", "1");    	
    	//To enable strict mode for android greater than 3.0
    	JSONParser jsonParser = new JSONParser();
    	JSONArray jArraylevel1 =  jsonParser.getJSONArray(url+ subjectId);
    	try {
			size = jArraylevel1.length();
			Log.d("jArraylevel1", "jArraylevel1.size()=" + size );
			int index = 0 ;
			for(int i = 0 ; i < size ; i++ ){
				//Log.d("bug i", "0" +i);
			  	index = i + 1;
			  	//Diem is an object mark for only one student
	            JSONObject Diem = jArraylevel1.getJSONObject(i);
	            //Analysis Diem array for a student:
	            JSONArray Diem28 = Diem.getJSONArray("mark");
	            //diemArray is a list of mark of a subject for a student
				int size28 = MarkModel.size_full;//defined 28 in MarkModel
	            Diem[] diemArray = new Diem[size28];
				for(int k = 0 ; k < size28 ; k ++) {
					diemArray[k] = new Diem(-1, true, -1, -1 ); // blank mark
				}
				for(int k = 0 ; k < Diem28.length() ; k ++) {
					JSONObject aDiem = Diem28.getJSONObject(k);					
					int number = aDiem.getInt("n");
					diemArray[number-1] = new Diem(Double.valueOf( aDiem.getString("m") ), editable(aDiem.getString("e")), number , aDiem.getInt("s"));
				}
	            list.add( new MarkModel(Diem.getString("id"), index, Diem.getString("firstName"), diemArray, Diem.getString("lastName"), Diem.getString("firstName") ) );
			}//end for.
			Log.d("bug", "end for");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//end try.

	}

	private boolean editable(String string) {
		// TODO Auto-generated method stub
		if(string.equals("0"))
			return false;
		return true;
	}
	public void test(){
		UserFunctions userFunction = new UserFunctions();
		JSONStringer string = new JSONStringer();//{"id":603031,"mark":[{"m":5.5,"n":1}]}
		try {	
			string = string.object()
					.key("id").value(603031)
					.key("mark")
						.array()
							.object()
							.key("m").value(10)
							.key("n").value(1)
							.endObject()
						.endArray()
					.endObject();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Log.d("submit", string.toString());
		int statusCode= userFunction.submitMark(url_submit_mark, string.toString());
	}
	public void submitMark(String string){//send one mark only
		Log.d("flag", "start");
		new submitATask().execute( url_submit_mark, string);		
	}
	public void submitMark(int i){
		//Send attendList to server.
		new submitTask().execute(i+"" , url_submit_mark+ subjectId);
	}
	public void submitMark(){//end all mark
		//Send attendList to server.
		new submitTask().execute(url_submit_mark+ subjectId);
	}
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
            Toast.makeText(getApplicationContext(), "onCreate Dialog", Toast.LENGTH_SHORT).show();
        }
        return null;
    }
    //submit a mark only
	class submitATask extends AsyncTask<String, Void, Void>{
		int statusCode;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
    		actionBar.setProgressBarVisibility(View.VISIBLE);
		}
		@Override
		protected Void doInBackground(String... params) {			
			UserFunctions userFunction = new UserFunctions();
			statusCode= userFunction.submitMark(params[0], params[1]);
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
    		actionBar.setProgressBarVisibility(View.VISIBLE);
			switch (statusCode) {
			case 200:{
				Toast.makeText(getApplicationContext(), "Đã nhập điểm lớp: "+ className, Toast.LENGTH_SHORT).show();
				finish();
				SubmitMark.this.overridePendingTransition(android.R.anim.slide_out_right, android.R.anim.slide_in_left);
				break;}
			case -1:{
				Toast.makeText(getApplicationContext(), "Diểm k có gì thay đổi lớp: "+className, Toast.LENGTH_SHORT).show();
				finish();
				SubmitMark.this.overridePendingTransition(android.R.anim.slide_out_right, android.R.anim.slide_in_left);
				break;}
			default:{
				Toast.makeText(getApplicationContext(), "Try again!!!!!!!!!!!!!!"+ className, Toast.LENGTH_SHORT).show();
				SubmitMark.this.overridePendingTransition(android.R.anim.slide_out_right, android.R.anim.slide_in_left);
				break;}
			}			
    		actionBar.setProgressBarVisibility(View.GONE);
		}
	}//End class
	class submitTask extends AsyncTask<String, Void, Void>{
		int statusCode;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
    		actionBar.setProgressBarVisibility(View.VISIBLE);
		}
		@Override
		protected Void doInBackground(String... params) {			
			UserFunctions userFunction = new UserFunctions();
			statusCode= userFunction.submitMark(list , subjectId, params[0]);
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
    		actionBar.setProgressBarVisibility(View.VISIBLE);
			switch (statusCode) {
			case 200:{
				Toast.makeText(getApplicationContext(), "Đã nhập điểm lớp: "+ className, Toast.LENGTH_SHORT).show();
				finish();
				SubmitMark.this.overridePendingTransition(android.R.anim.slide_out_right, android.R.anim.slide_in_left);
				break;}
			case -1:{
				Toast.makeText(getApplicationContext(), "Diểm k có gì thay đổi lớp: "+className, Toast.LENGTH_SHORT).show();
				finish();
				SubmitMark.this.overridePendingTransition(android.R.anim.slide_out_right, android.R.anim.slide_in_left);
				break;}
			default:{
				Toast.makeText(getApplicationContext(), "Try again!!!!!!!!!!!!!!"+ className, Toast.LENGTH_SHORT).show();
				SubmitMark.this.overridePendingTransition(android.R.anim.slide_out_right, android.R.anim.slide_in_left);
				break;}
			}			
    		actionBar.setProgressBarVisibility(View.GONE);
		}
	}//End class
	class GoogleMusicAdapter extends TestFragmentAdapter {
        public GoogleMusicAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
    		ArrayList<HashMap<String, String>> classList = new ArrayList<HashMap<String,String>>() ;

    		HashMap<String, String> titleClass = new HashMap<String, String>();
			titleClass.put("name", "STT. Họ tên");
			titleClass.put("mark_1", "1");
			titleClass.put("mark_2", "2");
			titleClass.put("mark_3", "3");
			titleClass.put("mark_4", "4");
			classList.add(titleClass);

    		for (int i = 0 ; i< size ; i++){
    			HashMap<String, String> aClass = new HashMap<String, String>();
    			aClass.put("name", i + "." + list.get(i).getName());    			
    			aClass.put("mark_1", String.valueOf(list.get(i).getDiem(0)));
    			aClass.put("mark_2", String.valueOf(list.get(i).getDiem(1)));
    			aClass.put("mark_3", String.valueOf(list.get(i).getDiem(2)));
    			aClass.put("mark_4", String.valueOf(list.get(i).getDiem(3)));
    			classList.add(aClass);
    		};//end for to initialize.
    		
    		Log.d("bug position = ", 8*position+"");
    		if(position == 3){
    			return new TestFragment(list, 8*position, 8*position+ 3);
    		}else{
    			return new TestFragment(list, 8*position, 8*position + 8 );
    		}
    	}

        @Override
        public int getCount() {
            return SubmitMark.CONTENT.length;
        }
        
        @Override
        public CharSequence getPageTitle(int position) {
            return SubmitMark.CONTENT[position % SubmitMark.CONTENT.length].toUpperCase();
        }
    }
	
    private class myAction extends AbstractAction {
    	private int actionId;
        public myAction(int actionId, int resId) {
            super(resId);
            this.actionId = actionId;
        }

        public void performAction(View view) {	
            		switch (actionId) {
					case HOME_ID://acition 0 touched! Back to home
			            Toast.makeText(SubmitMark.this,"Action Back to home", Toast.LENGTH_SHORT).show();
						if(mKeyboardView.getVisibility() == View.GONE)
							showKeyboardWithAnimation();
						else
							hideKeyboardWithAnimation();
			            //finish();
						break;
					case SUBMIT_ID://Action 1 touched! Submit to server
			            Toast.makeText(SubmitMark.this,"Action submit", Toast.LENGTH_SHORT).show();
			            test();
			            //submitMark();
						break;
					case DATE_ID://Action 1 touched! date
			            Toast.makeText(SubmitMark.this,"Action date", Toast.LENGTH_SHORT).show();
			            showDialog(DATE_DIALOG_ID);
						break;
					default:
						break;
					}
        }//end perform

    }//end myAction class
	private void showKeyboardWithAnimation() {
		if (mKeyboardView.getVisibility() == View.GONE) {
			Animation animation = AnimationUtils
					.loadAnimation(SubmitMark.this,
							R.anim.keyboard_slide_in_bottom);
			mKeyboardView.showWithAnimation(animation);
		}
	}
	private void hideKeyboardWithAnimation(){
		if(mKeyboardView.getVisibility() == View.VISIBLE){
			Animation animation = AnimationUtils
					.loadAnimation(SubmitMark.this, R.anim.keyboard_slide_out_bottom);
			mKeyboardView.hideWithAnimation(animation);
		}
	}

}//end class.
